package j5039.whcm.gateway.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.stream.Collectors;

@Configuration
public class MyCorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter(){
        //添加cors的配置信息
        CorsConfiguration configuration = new CorsConfiguration();
        //允许访问的域名
        configuration.addAllowedOrigin("http://admin.whcm.com");  //设置允许访问的域名或者id
        configuration.setAllowCredentials(true); //设置允许访问设置cookie
        configuration.addAllowedMethod("*");   //设置允许的请求方法
        configuration.addAllowedHeader("*");    //设置允许的请求头

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",configuration);
        return new CorsWebFilter(source);

    }

    @Bean
    @ConditionalOnMissingBean
    public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
        return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
    }

}
